package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.AdminApplication;
import com.heima.admin.mapper.AdUserDtoMapper;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserDtoService;
import com.heima.common.constants.admin.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.dtos.AdUserDto;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import com.heima.model.admin.vo.AdUserVO;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;

@Service
public class AdUserDtoServiceImpl extends ServiceImpl<AdUserMapper,AdUser> implements AdUserDtoService {
    @Override
    public ResponseResult login(AdUser dto) {
        //查询用户是否存在
        if (dto == null || StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())) {
//           CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //检查用户状态是否有效
        AdUser adUser = getOne(Wrappers.<AdUser>lambdaQuery()
                .eq( AdUser::getName, dto.getName() )
                .eq(AdUser::getStatus, AdminConstants.AD_USER_ISSTATUS));
        if (adUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"状态异常！！");
        }
        //检查密码是否正确
        String password = adUser.getPassword();
        String salt = adUser.getSalt();

        String newPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes());
        if (!password.equals(newPwd)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "用户名或者密码错误");
        }
        //修改登录时间
        adUser.setCreatedTime(new Date());
        updateById(adUser);
        //颁发token
        String token = AppJwtUtil.getToken(adUser.getId().longValue());
        AdUserVO adUserVo = new AdUserVO();
//        BeanUtils.copyProperties(adUser, adUserVo);
        BeanUtils.copyProperties(adUser,adUserVo);

        Map map = new HashMap();
        map.put("token", token);
        map.put("user", adUserVo);

        return ResponseResult.okResult(map);


    }
}
